package com.besall.allbase.view.activity.chipstoollevel4.customerdial.makedial;

import static com.bes.bessdk.BesSdkConstants.BES_WIFI_CHARACTERISTIC_TX_UUID;
import static com.bes.bessdk.BesSdkConstants.BES_WIFI_DESCRIPTOR_UUID;
import static com.bes.bessdk.BesSdkConstants.BES_WIFI_SERVICE_UUID;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CHOOSE_DIAL_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_FORM_VALUE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_LENGTH_VALUE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_PATH_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_WIDTH_VALUE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_FOLDER;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_FOLDER_CACHE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_FOLDER_CACHE_PHOTO_NAME;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOM_DIAL_COLORS;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.REQUEST_CODE_CROP_PHOTO;
import static com.besall.allbase.bluetooth.BluetoothConstants.Scan.REQUEST_CODE_CAPTURE_CAMEIA;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.bes.bessdk.service.base.BesServiceConfig;
import com.bes.bessdk.utils.SPHelper;
import com.bes.sdk.utils.DeviceProtocol;
import com.besall.allbase.bluetooth.BluetoothConstants;
import com.besall.allbase.common.manager.PermissionManager;
import com.besall.allbase.view.activity.chipstoollevel4.customerdial.CustomerDialBean;
import com.besall.allbase.view.activity.tools.actionsheet.ActionSheet;
import com.besall.allbase.view.activity.tools.actionsheet.ActionSheetListener;
import com.besall.allbase.view.base.BaseActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.UiThread;
import androidx.core.content.FileProvider;

import bb.lanxing.R;

/**
 * @author ericshen
 * @time $ $
 */
public class MakeDialActivity extends BaseActivity<IMakeDialActivity, MakeDialPresenter> implements IMakeDialActivity, View.OnClickListener, AdapterView.OnItemClickListener {
    private static MakeDialActivity instance;

    BesServiceConfig mServiceConfig;

    ListView list_view;
    MakeDialAdapter mAdapter;
    List<CustomerDialBean> mList;

    Button dial_button;

    TextView cur_dial_size;
    ImageView dial_show_image;
    LinearLayout dial_show_layout_number;
    LinearLayout dial_show_layout_icom;
    TextView dial_show_time_text;
    TextView dial_show_date_text;
    TextView photo_resolution;
    ImageView dial_tab_background_image;
    TextView dial_tab_background_text;
    ImageView dial_tab_style_image;
    TextView dial_tab_style_text;
    ImageView dial_tab_color_image;
    TextView dial_tab_color_text;

    int curTabIndex = 0;
    int curBackgroundIndex = 0;
    int curClickIndex = 0;

    int curNeedDialForm = 1;
    int curNeedDialLength = 0;
    int curNeedDialWidth = 0;

    private String takePhotoPath;
    private CustomerDialBean curDialBean;

    @Override
    protected MakeDialPresenter createPresenter() {
        return new MakeDialPresenter();
    }

    @Override
    protected void initBeforeSetContent() {
        mServiceConfig = new BesServiceConfig();
        mServiceConfig.setServiceUUID(BES_WIFI_SERVICE_UUID);
        mServiceConfig.setCharacteristicsUUID(BES_WIFI_CHARACTERISTIC_TX_UUID);
        mServiceConfig.setDescriptorUUID(BES_WIFI_DESCRIPTOR_UUID);
        mServiceConfig.setTotaConnect(false);
        mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);

        mList = getBackGroundList();
        if (curBackgroundIndex > 0)
            curDialBean = mList.get(curBackgroundIndex);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_makedial;
    }

    @Override
    protected void bindView() {
        cur_dial_size = (TextView) findViewById(R.id.cur_dial_size);
        dial_show_image = (ImageView) findViewById(R.id.image_item);
        dial_show_layout_number = (LinearLayout) findViewById(R.id.function_item_bottom);
        dial_show_layout_icom = (LinearLayout) findViewById(R.id.function_item_icon);
        dial_show_time_text = (TextView) findViewById(R.id.date_textview_bottom);
        dial_show_date_text = (TextView) findViewById(R.id.time_textview_bottom);
        list_view = (ListView) findViewById(R.id.list_view);
        dial_button = (Button) findViewById(R.id.dial_button);
        dial_tab_background_image = (ImageView) findViewById(R.id.dial_tab_background_image);
        dial_tab_background_text = (TextView) findViewById(R.id.dial_tab_background_text);
        dial_tab_style_image = (ImageView) findViewById(R.id.dial_tab_style_image);
        dial_tab_style_text = (TextView) findViewById(R.id.dial_tab_style_text);
        dial_tab_color_image = (ImageView) findViewById(R.id.dial_tab_color_image);
        dial_tab_color_text = (TextView) findViewById(R.id.dial_tab_color_text);
        photo_resolution = (TextView) findViewById(R.id.photo_resolution);
    }

    @SuppressLint("ResourceAsColor")
    @Override
    protected void initView() {
        String titleStr = "CHOOSE DIAL";
        tv_title.setText(titleStr);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        mAdapter = new MakeDialAdapter();

        curNeedDialForm = (int) SPHelper.getPreference(instance, CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY, CUSTOMER_DIAL_CROP_PHOTO_FORM_VALUE);
        curNeedDialLength = (int) SPHelper.getPreference(instance, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_VALUE);
        curNeedDialWidth = (int) SPHelper.getPreference(instance, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_VALUE);
        cur_dial_size.setText(getString(R.string.current_dial_size) + " " + (curNeedDialForm == 2 ? getString(R.string.form_square) : getString(R.string.form_circle)) + " " + curNeedDialLength + "x" + curNeedDialWidth);

        list_view.setSelector(new ColorDrawable(Color.TRANSPARENT));
        list_view.setAdapter(mAdapter);
        list_view.setOnItemClickListener(instance);
        dial_button.setOnClickListener(instance);
        dial_tab_background_image.setImageResource(R.drawable.bg_dial_pressed);
        dial_tab_background_text.setTextColor(R.color.title_color);

        dial_tab_background_image.setOnClickListener(instance);
        dial_tab_style_image.setOnClickListener(instance);
        dial_tab_color_image.setOnClickListener(instance);

        takePhotoPath = new com.besall.allbase.common.utils.FileUtils(instance).getFilesDir(CUSTOMER_DIAL_FOLDER_CACHE_PHOTO_NAME, CUSTOMER_DIAL_FOLDER_CACHE);
    }

    @Override
    protected void setInstance() {
        instance = this;
    }

    @Override
    protected void removeInstance() {
        instance = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA) {
            mPresenter.cropPhoto(instance, REQUEST_CODE_CROP_PHOTO);
        } else if (requestCode == BluetoothConstants.Scan.REQUEST_CODE_CHOOSE_PHOTO) {
            try {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String path = cursor.getString(columnIndex);
                cursor.close();

                InputStream is = new FileInputStream(path);
                FileOutputStream fos = new FileOutputStream(takePhotoPath);
                byte[] buffer = new byte[1024];
                int count = 0;
                while((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mPresenter.cropPhoto(instance, REQUEST_CODE_CROP_PHOTO);
        } else if (requestCode == REQUEST_CODE_CROP_PHOTO) {
            String path = data.getStringExtra(CUSTOMER_DIAL_CROP_PHOTO_PATH_KEY);
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            dial_show_image.setImageBitmap(bitmap);
            mList = getBackGroundList();
            mAdapter.refresh();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == android.R.id.home){
            finish();
        }

/*        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }*/
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
    	
    	
        if(v.getId() == R.id.dial_tab_background_image){
        	 onTabClick(0);
     }else if(v.getId() == R.id.dial_tab_style_image){
    	 onTabClick(1);
     }else if(v.getId() == R.id.dial_tab_color_image){
    	 onTabClick(2);
     }else if(v.getId() == R.id.dial_button){
         Intent intent = new Intent();
         intent.putExtra(CUSTOMER_DIAL_CHOOSE_DIAL_KEY, curDialBean);
         setResult(RESULT_OK, intent);
         finish();
     }
    	
/*        switch (v.getId()) {
            case R.id.dial_tab_background_image:
                onTabClick(0);
                break;
            case R.id.dial_tab_style_image:
                onTabClick(1);
                break;
            case R.id.dial_tab_color_image:
                onTabClick(2);
                break;
            case R.id.dial_button:
                Intent intent = new Intent();
                intent.putExtra(CUSTOMER_DIAL_CHOOSE_DIAL_KEY, curDialBean);
                setResult(RESULT_OK, intent);
                finish();
                break;
            default:
                break;
        }*/
    }

    @SuppressLint("ResourceAsColor")
    private void onTabClick(int tabIndex) {
        if (getBackGroundList().size() == 2 || curDialBean == null) {
            showToast(R.string.choose_dial);
            return;
        }
        curClickIndex = -1;
        curTabIndex = tabIndex;
        dial_tab_background_image.setImageResource(R.drawable.bg_dial_noraml);
        dial_tab_background_text.setTextColor(R.color.black);
        dial_tab_style_image.setImageResource(R.drawable.ic_dail_normal);
        dial_tab_style_text.setTextColor(R.color.black);
        dial_tab_color_image.setImageResource(R.drawable.ic_dial_normal);
        dial_tab_color_text.setTextColor(R.color.black);

        if (curTabIndex == 0) {
            dial_tab_background_image.setImageResource(R.drawable.bg_dial_pressed);
            dial_tab_background_text.setTextColor(R.color.title_color);
            mList = getBackGroundList();
        } else if (curTabIndex == 1) {
            dial_tab_style_image.setImageResource(R.drawable.ic_dail_pressed);
            dial_tab_style_text.setTextColor(R.color.title_color);
            mList = getStyleList();
        } else if (curTabIndex == 2) {
            dial_tab_color_image.setImageResource(R.drawable.ic_dial_pressed);
            dial_tab_color_text.setTextColor(R.color.title_color);
            mList = getColorList();
        }

        mAdapter.refresh();
    }

    private List<CustomerDialBean> getBackGroundList() {
        List<CustomerDialBean> list = new ArrayList<>();
        list.add(new CustomerDialBean());
        String dirPath = instance.getExternalFilesDir("").getAbsolutePath() + "/" + CUSTOMER_DIAL_FOLDER;
        File fatherFile = new File(dirPath);
        if (!fatherFile.exists()) {
            fatherFile.mkdirs();
        }
        File[] files = fatherFile.listFiles();
//        if (files.length > 0 && curBackgroundIndex == 0) {
//            curBackgroundIndex = 1;
//        }
        for (int i = 0; i < files.length; i ++) {
            CustomerDialBean bean = new CustomerDialBean();
            bean.setBackground(i + 1);
            bean.setPath(files[i].getAbsolutePath());
            list.add(bean);
        }

        list.add(new CustomerDialBean());
        return list;
    }

    private List<CustomerDialBean> getStyleList() {
        List<CustomerDialBean> list = new ArrayList<>();
        for (int i = 0; i < 2; i ++) {
            CustomerDialBean bean = new CustomerDialBean();
            bean.setPath(curDialBean.getPath());
            bean.setStyle(i);
            bean.setColor(0);
            list.add(bean);
        }

        list.add(new CustomerDialBean());
        return list;
    }

    private List<CustomerDialBean> getColorList() {
        List<CustomerDialBean> list = new ArrayList<>();
        for (int i = 0; i < CUSTOM_DIAL_COLORS.length - 1; i ++) {
            CustomerDialBean bean = new CustomerDialBean();
            bean.setPath(curDialBean.getPath());
            bean.setStyle(1);
            bean.setColor(i);
            list.add(bean);
        }

        list.add(new CustomerDialBean());
        return list;
    }

    protected void showToast(int msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == (mList.size() - 1)) {
            return;
        }

        if (curTabIndex == 0) {
            if (position == 0) {
                showActionSheet();
                return;
            }
            curBackgroundIndex = position;
            curDialBean = mList.get(position);
            Bitmap bitmap = BitmapFactory.decodeFile(curDialBean.getPath());
            photo_resolution.setText(bitmap.getHeight() + " * " + bitmap.getWidth());
            dial_show_image.setImageBitmap(bitmap);
        } else if (curTabIndex == 1) {
            curDialBean.setStyle(position);
        } else if (curTabIndex == 2) {
            curDialBean.setColor(position);
        }

        if (curDialBean.getStyle() == 0) {
            dial_show_layout_icom.setVisibility(View.VISIBLE);
            dial_show_layout_number.setVisibility(View.GONE);
        } else {
            dial_show_layout_icom.setVisibility(View.GONE);
            dial_show_layout_number.setVisibility(View.VISIBLE);
            if (curDialBean.getColor() > -1) {
                dial_show_time_text.setTextColor(Color.parseColor(CUSTOM_DIAL_COLORS[curDialBean.getColor()]));
                dial_show_date_text.setTextColor(Color.parseColor(CUSTOM_DIAL_COLORS[curDialBean.getColor()]));
            }
        }

        curClickIndex = position;
        mAdapter.refresh();

        Bitmap bitmap = BitmapFactory.decodeFile(curDialBean.getPath());
        if (bitmap.getHeight() == curNeedDialLength && bitmap.getWidth() == curNeedDialWidth) {
            dial_button.setText(getText(R.string.choose_dial));
            dial_button.setBackground(getDrawable(R.drawable.ota_button_bg));
            dial_button.setEnabled(true);
        } else {
            dial_button.setText(getText(R.string.current_dial));
            dial_button.setBackground(getDrawable(R.drawable.ota_button_bg_press));
            dial_button.setEnabled(false);
        }
    }

    private void showActionSheet() {
        ActionSheet actionSheet = new ActionSheet(instance, new String[]{getString(R.string.action_sheet_item0), getString(R.string.action_sheet_item1)}, new ActionSheetListener() {
            @Override
            public void didSelectItem(int index) {
                if (index == 0) {
                    requestPermissionForCamera();
                } else if (index == 1) {
                    startChoosePhoto();
                }
            }
        });
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                actionSheet.show();
            }
        });
    }

    private void requestPermissionForCamera() {
        PermissionManager.getInstance().requestPermissions(this, new PermissionManager.PermissionUtilListener() {
            @Override
            public void onGranted() {
                startTakePhoto();
            }

            @Override
            public void onUngranted(String msg) {

            }

            @Override
            public void onError(String msg) {

            }
        }, Manifest.permission.CAMERA);

    }

    private void startTakePhoto() {
        File file = new File(takePhotoPath);
        if (file.exists()) {
            file.delete();
        }
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Uri fileUri;
            if (Build.VERSION.SDK_INT >= 24) {
                fileUri = FileProvider.getUriForFile(this, "bb.lanxing.FileProvider", new File(takePhotoPath));//bb.lanxing //com.makedial.FileProvider
            } else {
                fileUri = Uri.fromFile(new File(takePhotoPath));
            }
            Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0.5);
            getImageByCamera.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
        }
    }

    private void startChoosePhoto() {
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, BluetoothConstants.Scan.REQUEST_CODE_CHOOSE_PHOTO);
    }

    class MakeDialAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public MakeDialAdapter() {
            super();
            mInflater = LayoutInflater.from(instance);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            CustomerDialBean bean = mList.get(position);
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.make_dial_list_item, parent, false);
                holder = new ViewHolder();

                holder.image_item = (ImageView) convertView.findViewById(R.id.image_item);
                holder.image_item_big = (View) convertView.findViewById(R.id.image_item_big);

                holder.function_item_bottom = (LinearLayout) convertView.findViewById(R.id.function_item_bottom);
                holder.date_textview_bottom = (TextView) convertView.findViewById(R.id.date_textview_bottom);
                holder.time_textview_bottom = (TextView) convertView.findViewById(R.id.time_textview_bottom);
//                holder.function_textview_bottom = (TextView) convertView.findViewById(R.id.function_textview_bottom);
//                holder.function_item_top = (LinearLayout) convertView.findViewById(R.id.function_item_top);
//                holder.date_textview_top = (TextView) convertView.findViewById(R.id.date_textview_top);
//                holder.time_textview_top = (TextView) convertView.findViewById(R.id.time_textview_top);
//                holder.function_textview_top = (TextView) convertView.findViewById(R.id.function_textview_top);
                holder.function_item_icon = (LinearLayout) convertView.findViewById(R.id.function_item_icon);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (bean.getPath().length() > 0) {
                Bitmap bitmap = BitmapFactory.decodeFile(bean.getPath());
                holder.image_item.setImageBitmap(bitmap);
            }
            if (position == (mList.size() - 1)) {
                holder.image_item.setImageResource(0);
            }
            if (curTabIndex == 0 && position == 0) {
                holder.image_item.setImageResource(R.drawable.ic_customer_dial_add);
            }

            holder.image_item_big.setVisibility(View.INVISIBLE);
            if (curBackgroundIndex > 0 && curClickIndex == position) {
                holder.image_item_big.setVisibility(View.VISIBLE);
            }
            if (curTabIndex == 0 && position == 0) {
                holder.image_item_big.setVisibility(View.INVISIBLE);
            }

            if (bean.getStyle() < 0 || bean.getColor() < 0) {
                holder.function_item_icon.setVisibility(View.GONE);
                holder.function_item_bottom.setVisibility(View.GONE);
            } else {
                if (bean.getStyle() == 0) {
                    holder.function_item_icon.setVisibility(View.VISIBLE);
                    holder.function_item_bottom.setVisibility(View.GONE);
                } else {
                    holder.function_item_icon.setVisibility(View.GONE);
                    holder.function_item_bottom.setVisibility(View.VISIBLE);
                }
            }
            if (curTabIndex == 2) {
                holder.date_textview_bottom.setTextColor(Color.parseColor(CUSTOM_DIAL_COLORS[position]));
                holder.time_textview_bottom.setTextColor(Color.parseColor(CUSTOM_DIAL_COLORS[position]));
            }
            return convertView;
        }

        @UiThread
        public void refresh() {
            notifyDataSetChanged();
        }

    }

    class ViewHolder {
        ImageView image_item;
        View image_item_big;
//        LinearLayout function_item_top;
//        TextView date_textview_top;
//        TextView time_textview_top;
//        TextView function_textview_top;
        LinearLayout function_item_bottom;
        TextView date_textview_bottom;
        TextView time_textview_bottom;

        LinearLayout function_item_icon;

//        TextView function_textview_bottom;

    }

}
